<template>
  <div>
    <div class="search">
      <Row>
        <Col>
          <Card>
            <Row>
              <Form ref="searchForm" :model="searchForm" inline :label-width="100" class="search-form">
                <Form-item label="公司名称" prop="">
                  <Input v-model="searchForm.name" style="width: 260px;"/>
                </Form-item>
                <Form-item style="margin-left:-100px;" class="br">
                  <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                  <Button @click="handleReset">重置</Button>
                </Form-item>
              </Form>
            </Row>
            <Row class="operation">
              <Button @click="addFacilitator" type="primary" icon="md-add">添加入围公司</Button>
              <Button @click="editFacilitator" type="warning" icon="ios-bookmarks-outline" >编辑入围公司</Button>
              <Dropdown @on-click="handleDropdown">
                <Button>
                  更多操作
                  <Icon type="md-arrow-dropdown" />
                </Button>
                <DropdownMenu slot="list">
                  <DropdownItem name="exportData">导出所选数据</DropdownItem>
                  <DropdownItem name="exportAll">导出全部数据</DropdownItem>
                  <DropdownItem name="changeActive">公司状态转换</DropdownItem>
                  <DropdownItem name="changeName">修改公司名称</DropdownItem>
                </DropdownMenu>
              </Dropdown>
              <Button @click="refresh" icon="refresh">刷新</Button>
            </Row>
            <Row>
              <Alert show-icon>
                已选择 <span class="select-count">{{selectCount}}</span> 项
                <a class="select-clear" @click="clearSelectAll">清空</a>
              </Alert>
            </Row>
            <Row>
              <Table
                border
                :loading="loading"
                :columns="columns"
                :data="data"
                sortable="custom"
                @on-selection-change="showSelect"
                ref="table">
              </Table>
              <Table :columns="exportColumns" :data="exportData" ref="exportTable" style="display:none"></Table>
            </Row>
            <Row type="flex" justify="end" class="page">
              <Page
                :current="searchForm.pageNumber"
                :total="total"
                :page-size="searchForm.pageSize"
                @on-change="changePage"
                @on-page-size-change="changePageSize"
                :page-size-opts="[10,20,50]"
                size="small"
                show-total
                show-elevator
                show-sizer
              ></Page>
            </Row>
          </Card>
        </Col>
      </Row>
      <Modal v-model="modalExportAll" title="确认导出" :loading="loadingExport" @on-ok="exportAll">
        <p>您确认要导出全部 {{total}} 条数据？</p>
      </Modal>
      <Modal v-model="modalChangeName" title="修改公司名称" @on-ok="changeName">
        <p>公司名称<Input v-model="changeCompanyName" style="width: 260px;"/></p>
      </Modal>
      <Modal v-model="accountVisiable" title="银行账户信息"  :styles="{top: '350px'}">
        <table width="90%">
          <tr v-for="(item,index) in accountData" :key="index">
            <td>
              开户银行：{{ item.bank_name }} <br/>
              银行账户：{{ item.bank_account }}
            </td>
          </tr>
        </table>
      </Modal>
      <addEdit :data="form" :type="showType" v-model="addEditVisiable" @on-submit="refresh"/>
    </div>
  </div>
</template>
<script>
import { getFacilitator, updateFacilitator, getAllFacilitator, getBankAccount, checkName } from '@/api/company';
import { getStore } from '@/libs/storage';
import util from '@/libs/util';
import addEdit from './addEdit';
export default {
  name: 'facilitator-manager',
  components: {
    addEdit
  },
  data() {
    return {
      loading: false,
      searchForm: {
        name: '',
        pageNumber: 1,
        pageSize: 10
      },
      data: [],
      total: 0,
      selectCount: 0,
      exportData: [],
      selectList: [],
      accountData: [],
      modalExportAll: false,
      form: {},
      showType: '',
      addEditVisiable: false,
      loadingExport: false,
      accountVisiable: false,
      changeCompanyName: '',
      modalChangeName: false,
      columns: [
        {
          type: "selection",
          width: 50,
          align: "center",
          fixed: "left"
        },
        {
          type: "index",
          width: 50,
          align: "center",
          fixed: "left"
        },
        {
          title: '公司名称',
          key: 'name',
          width: 240
        },
        {
          title: '开户行',
          key: 'action',
          width: 60,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'text',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.viewAccount(params.row)
                  }
                }
              }, '账户'),
            ]);
          }
        },
        {
          title: '地址',
          key: 'address',
          width: 160
        },
        {
          title: '企业机构代码',
          key: 'credit_code',
          width: 160
        },
        {
          title: '承包资质',
          key: 'professional_qualification',
          
          width: 160
        },
        {
          title: '承装修资质',
          key: 'qualification',
          align: 'center',
          width: 180
        },
        {
          title: '安全无事故证明',
          key: 'security_certificate',
          align: "center",
          width: 70,
          render: (h, params) => {
            if (params.row.security_certificate == 1) {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "success",
                    text: "有"
                  }
                })
              ]);
            } else {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "error",
                    text: "无"
                  }
                })
              ]);
            }
          }
        },
        {
          title: '安全生产许可证',
          key: 'licence',
          align: "center",
          width: 70,
          render: (h, params) => {
            if (params.row.licence == 1) {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "success",
                    text: "有"
                  }
                })
              ]);
            } else {
              return h("div", [
                h("Badge", {
                  props: {
                    status: "error",
                    text: "无"
                  }
                })
              ]);
            }
          }
        },
        {
          title: '联系人',
          key: 'contacts',
          align: 'center',
          width: 80
        },
        {
          title: '电话',
          key: 'mobile',
          align: 'center',
          width: 110
        },
        {
          title: '状态',
          key: 'is_active',
          align: 'center',
          width: 80,
          render: (h, params) => {
            if (params.row.is_active == 0) {
              return h("div", {style: { color: 'red'}}, '出局');
            } else {
              return h("div", {style: { color: 'green'}}, '入围');
            }
          },
        },
        {
          title: '添加人',
          key: 'real_name',
          align: 'center',
          width: 80
        },
      ],
      exportColumns: [
        {
          title: '公司名称',
          key: 'name',
        },
        {
          title: '地址',
          key: 'address',
        },
        {
          title: '企业机构代码',
          key: 'credit_code',
        },
        {
          title: '承包资质',
          key: 'professional_qualification',
        },
        {
          title: '承装修资质',
          key: 'qualification',
        },
        {
          title: '安全无事故证明',
          key: 'security_certificate',
        },
        {
          title: '安全生产许可证',
          key: 'licence',
        },
        {
          title: '联系人',
          key: 'contacts',
          align: 'center',
          width: 80
        },
        {
          title: '电话',
          key: 'mobile',
          align: 'center',
          width: 110
        },
        {
          title: '状态',
          key: 'is_active',
        }
      ],
    }
  },
  methods: {
    handleSearch() {
      this.searchForm.name = this.searchForm.name.trim();
      this.getFacilitatorList();
    },
    handleReset() {
      this.searchForm.name = '';
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.getFacilitatorList();
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false);
    },
    showSelect(e) {
      this.exportData = e;
      this.selectList = e;
      this.selectCount = e.length;
    },
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getFacilitatorList();
    },
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.getFacilitatorList();
    },
    refresh() {
      this.getFacilitatorList();
    },
    getFacilitatorList() {
      this.loading = true;
      getFacilitator(this.searchForm).then(res => {
        if (res.code === 0) {
          this.data = res.data.raws;
          this.total = res.data.count;
        }
      })
      this.loading = false;
    },
    init() {
      this.getFacilitatorList();
    },
    viewAccount(v) {
      let params = {};
      params.company_type = 1;
      params.company_id = v.id;
      getBankAccount(params).then(res => {
        if (res.code === 0) {
          this.accountData = res.data.filter(item => item.is_active == 1);
          if (this.accountData.length > 0) {
            this.accountVisiable = true;
          } else {
            this.$Message.warning('没有对应的银行账户信息，请添加');
            return;
          }
        }
      })
    },
    addFacilitator() {
      const hasPermission = util.oneOf('add', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      }; 
      this.form = {};
      this.showType = '1';
      this.addEditVisiable = true;
    },
    editFacilitator() {
      const hasPermission = util.oneOf('edit', this.$route.meta.permTypes);
      if (!hasPermission) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      }; 
      if (this.selectList.length !== 1) {
        this.$Message.error('必须且只能选择一条记录进行编辑操作');
        return;
      }
      const current_organization_id = JSON.parse(getStore('userInfo')).organization_id;
      if (this.selectList[0].organization_id !== current_organization_id) {
        this.$Message.error('抱歉，您没有操作权限！');
        return;
      }
      // 转换null为""
      let v = this.selectList[0];
      for (let attr in v) {
        if (v[attr] == null) {
          v[attr] = "";
        }
      }
      let str = JSON.stringify(v);
      let data = JSON.parse(str);
      this.form = data;
      this.showType = '2';
      this.addEditVisiable = true;
    },
    handleDropdown(name) {
      let hasPermission;
      let current_organization_id;
      switch(name) {
        case 'changeActive':
          hasPermission = util.oneOf('edit', this.$route.meta.permTypes);
          if (!hasPermission) {
            this.$Message.error('抱歉，您没有操作权限！');
            return;
          }; 
          if (this.selectList.length !== 1) {
            this.$Message.error('必须且只能选择一条记录进行编辑操作');
            return;
          }
          current_organization_id = JSON.parse(getStore('userInfo')).organization_id;
          if (this.selectList[0].organization_id !== current_organization_id) {
            this.$Message.error('抱歉，您没有操作权限！');
            return;
          }
          const is_active = this.selectList[0].is_active == 1 ? 0 : 1;
          const params = {id: this.selectList[0].id, is_active};
          updateFacilitator(params).then(res => {
            if (res.code === 0) {
              this.$Message.success(res.message);
              this.getFacilitatorList();
            }
          })
          break;
        case 'exportData':
          if (this.selectCount <= 0) {
            this.$Message.warning("您还未选择要导出的数据");
            return;
          }
          this.$Modal.confirm({
            title: "确认导出",
            content: "您确认要导出所选 " + this.selectCount + " 条数据?",
            onOk: () => {
              this.$refs.exportTable.exportCsv({
                filename: "入围劳务分包公司数据"
              });
            }
          });
          break;
        case 'exportAll':
          this.modalExportAll = true;
          break;
        case 'changeName':
          hasPermission = util.oneOf('edit', this.$route.meta.permTypes);
          if (!hasPermission) {
            this.$Message.error('抱歉，您没有操作权限！');
            return;
          }; 
          if (this.selectList.length !== 1) {
            this.$Message.error('必须且只能选择一条记录进行编辑操作');
            return;
          }
          current_organization_id = JSON.parse(getStore('userInfo')).organization_id;
          if (this.selectList[0].organization_id !== current_organization_id) {
            this.$Message.error('抱歉，您没有操作权限！');
            return;
          }
          this.changeCompanyName = this.selectList[0].name;
          this.modalChangeName = true;
          break;
      }
    },
    // _checkPermission() {
    //   const hasPermission = util.oneOf('edit1', this.$route.meta.permTypes);
    //   if (!hasPermission) {
    //     this.$Message.error('抱歉，您没有操作权限！');
    //     return false;
    //   }; 
    //   if (this.selectList.length !== 1) {
    //     this.$Message.error('必须且只能选择一条记录进行编辑操作');
    //     return false;
    //   }
    //   current_organization_id = JSON.parse(getStore('userInfo')).organization_id;
    //   if (this.selectList[0].organization_id !== current_organization_id) {
    //     this.$Message.error('抱歉，您没有操作权限！');
    //     return false;
    //   }
    //   return true;
    // },
    changeName() {
      const name = this.changeCompanyName.trim();
      checkName({name}).then(res => {
        if (res.code === 0) {
          let params = {
            id: this.selectList[0].id,
            name
          };
          updateFacilitator(params).then(res => {
            if (res.code === 0) {
              this.$Message.success(res.message);
              this.modalChangeName = false;
              this.getFacilitatorList();
              return
            }
          })
        } else {
          this.$Message.error(res.message);
          return;
        }
      })
    },
    exportAll() {
      getAllFacilitator().then(res => {
        this.modalExportAll = false;
        if (res.code === 0) {
          this.exportData = res.data;
          setTimeout(() => {
            this.$refs.exportTable.exportCsv({
              filename: "入围劳务分包公司全部数据"
            });
          }, 1000);
        }
      });
    },
  },
  mounted() {
    this.init()
  }
}
</script>
<style lang="less" scoped>
@import "./facilitatorManager.less";
</style>